// 导入正则校验函数
let listMid = (req, res, next) => {
  // 接受name,age参数并进行校验
  let { current, pagesize, search, filter, saleType, sortType, sortMethod, category } = req.query;

  // 正则校验
  if (current && !/^[1-9]\d*$/.test(current)) return next({ code: 3, message: '参数current格式错误' });
  if (pagesize && !/^[1-9]\d*$/.test(pagesize)) return next({ code: 3, message: '参数pagesize格式错误' });
  if (filter && !/^(hot|sale)$/.test(filter)) return next({ code: 3, message: '参数filter格式错误' });
  if (saleType && !/^(5|6|7|8|9|10)$/.test(saleType)) return next({ code: 3, message: '参数saleType格式错误' });
  if (sortType && !/^(id|sale|price)$/.test(sortType)) return next({ code: 3, message: '参数sortType格式错误' });
  if (sortMethod && !/^(ASC|DESC)$/.test(sortMethod)) return next({ code: 3, message: '参数sortMethod格式错误' });
  next();
}

let detailMid = (req, res, next) => {
  let id = req.query.id ?? req.body.id;
  if (!id) return next({ code: 2, message: '参数id必须传递' });
  next();
}

let upMid = (req, res, next) => {
  let { id, price, current_price, sale_type, goods_number, is_hot, is_sale } = req.body;
  let data = { id, price, current_price, sale_type, goods_number, is_hot, is_sale };
  // 不为空校验
  for (let key in data) if (!data[key] && key != 'is_hot' && key != 'is_sale') return next({ code: 2, message: `参数${key}必须传递` });

  if (!/^[1-9]\d*.?\d*$/.test(price)) return next({ code: 3, message: `参数price格式错误` });
  if (!/^[1-9]\d*.?\d*$/.test(current_price)) return next({ code: 3, message: `参数current_price格式错误` });
  if (!/^(5|6|7|8|9|10)$/.test(sale_type)) return next({ code: 3, message: `参数sale_type格式错误` });
  if (!/^[1-9]\d*$/.test(goods_number)) return next({ code: 3, message: `参数goods_number格式错误` });
  if (!/^(1|0)\d*$/.test(is_hot)) return next({ code: 3, message: `参数is_hot格式错误` });
  if (!/^(1|0)\d*$/.test(is_sale)) return next({ code: 3, message: `参数is_sale格式错误` });

  if (price * (sale_type / 10) != current_price) return next({ code: 3, message: `参数折扣计算错误` });

  next();
}


let addMid = (req, res, next) => {
  let { title, img_big_logo, img_small_logo, price, sale_type, goods_number, is_hot, category, introduce } = req.body;
  let data = {
    title, img_big_logo, img_small_logo, price, sale_type, goods_number, is_hot, category, introduce
  }
  // 遍历data 不为空
  for (const key in data) if (!data[key] && key != 'is_hot') return next({ code: 2, message: `参数${key}必须传递` })

  // 格式校验
  if (!/^[1-9]\d*.?\d*$/.test(price)) return next({ code: 3, message: `参数price格式错误` });
  if (!/^[1-9]\d*$/.test(goods_number)) return next({ code: 3, message: `参数goods_number格式错误` });
  if (!/^(1|0)\d*$/.test(is_hot)) return next({ code: 3, message: `参数is_hot格式错误` });
  // if (!/^(1|0)\d*$/.test(introduce)) return next({ code: 3, message: `参数is_hot格式错误` });
  next()
}

module.exports = {
  listMid, detailMid, upMid, addMid

}